﻿using System;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Validation;

namespace Bricks.EnterpriseLibrary.Validation
{

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TTarget"></typeparam>
    public class ValidatorFacade<TTarget> : Bricks.Validation.ValidatorFacadeBase<TTarget, Validator<TTarget>>, IValidatorFacade<TTarget>
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="validator"></param>
        public ValidatorFacade(Validator<TTarget> validator) :
            base(() => validator)
        {
            if (validator == null)
            {
                throw new ArgumentNullException("validator");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public override IEnumerable<Bricks.Validation.ValidationResult> Validate(object target)
        {
            return Execute<IEnumerable<Bricks.Validation.ValidationResult>>(validator => Convert(validator.Validate(target)));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public override IEnumerable<Bricks.Validation.ValidationResult> Validate(TTarget target)
        {
            return Execute<IEnumerable<Bricks.Validation.ValidationResult>>(validator => Convert(validator.Validate(target)));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="validationResults"></param>
        /// <returns></returns>
        protected IEnumerable<Bricks.Validation.ValidationResult> Convert(ValidationResults validationResults)
        {
            foreach (ValidationResult validationResult in validationResults)
            {
                yield return new Bricks.Validation.ValidationResult(validationResult.Message, validationResult.Target, validationResult.Key, validationResult.Tag, this);
            }
        }
    }
}
